<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        function ajax(options) {
            var defaults = {
                type: 'get',
                url: '',
                data: {},
                header: {

                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                success: function() {},
                error: function() {}
            }
            Object.assign(defaults, options)
            var xhr = new XMLHttpRequest();
            var params = '';

            for (var attr in defaults.data) {
                params += attr + '=' + defaults.data[attr] + '&';
            }
            params = params.substr(0, params.length - 1)
            console.log(params)
            if (defaults.type == 'get') {
                defaults.url = defaults.url + '?' + params;
            }
            xhr.open(defaults.type, defaults.url);
            if (defaults.type == 'post') {
                var contentType = defaults.header['Content-Type'];
                xhr.setRequestHeader('Content-Type', contentType);
                if (contentType == 'application/json') {
                    xhr.send(JSON.stringify(defaults.data));
                } else {
                    xhr.send(params);
                }

            } else {
                xhr.send()
            }

            xhr.onload = function() {
                var responseText = xhr.responseText;
                var contentType = xhr.getResponseHeader('Content-Type')
                if (contentType.includes('application/json')) {
                    responseText = JSON.parse(responseText)
                }
                if (xhr.status == 200) {
                    defaults.success(responseText, xhr)
                } else {
                    defaults.error(responseText, xhr)
                }
            }
        }
        ajax({
            type: 'post',
            header: {
                "Content-Type": 'application/json'
            },
            url: "http://localhost:3000/first",

            data: {
                name: 'zhangsan',
                age: 12
            },
            success: function(date) {
                console.log('这里是ajax函数')
                console.log(date)
            },
            error: function(date) {
                console.log(date)

            }
        })
    </script>
</body>

</html>